<?php
/**
 * producer:每N秒读取一次司机在redis中的GPS数据，并构建好放入推送队列中
 */

define('APP_ROOT', __DIR__);

$apiName = 'JSYDW';

/*
每30秒从redis中读取 $realDriverIds 的gps数据,对应到 demo中的司机数据,
组建后保存到redis队列中
*/
// 10个司机
$drivers = [
    [
        'licenseId'   => '51020219630827064x',
        'driverPhone' => '13650522350',
        'vehicleNo'   => '渝AU212F',
        'driverName'  => '李昌碧'
    ],
    [
        'licenseId'   => '510923198605151221',
        'driverPhone' => '15723337725',
        'vehicleNo'   => '渝AB553S',
        'driverName'  => '廖禄强'
    ],
    [
        'licenseId'   => '510221196312112117',
        'driverPhone' => '18602336938',
        'vehicleNo'   => '渝AV233T',
        'driverName'  => '余学中'
    ],
    [
        'licenseId'   => '510213196412134719',
        'driverPhone' => '15823073335',
        'vehicleNo'   => '渝AB553R',
        'driverName'  => '吴家均'
    ],
    [
        'licenseId'   => '510226197008067995',
        'driverPhone' => '18702378808',
        'vehicleNo'   => '渝AX713T',
        'driverName'  => '戴华明'
    ],
    [
        'licenseId'   => '510225197508156445',
        'driverPhone' => '15086858756',
        'vehicleNo'   => '渝AY560X',
        'driverName'  => '余昭兰'
    ],
    [
        'licenseId'   => '513031197710176078',
        'driverPhone' => '13983381668',
        'vehicleNo'   => '渝AK012Q',
        'driverName'  => '刘艳林'
    ],
    [
        'licenseId'   => '512923197905175751',
        'driverPhone' => '15922956628',
        'vehicleNo'   => '渝AV710M',
        'driverName'  => '杨福建'
    ],
    [
        'licenseId'   => '50022119890130451X',
        'driverPhone' => '15823671930',
        'vehicleNo'   => '渝AU258F',
        'driverName'  => '陈伟'
    ],
    [
        'licenseId'   => '510215197110036934',
        'driverPhone' => '13368330822',
        'vehicleNo'   => '渝AQ793N',
        'driverName'  => '廖红'
    ]
];

$realDrivers = [
    '17898670839', '13617641612', '15803059836', '18444444444', '13206141938', '13647639216', '15823429910','15826041423','17898670111','17898670222'
];
//die('select driver_id,driver_phone from netcar_driver where driver_phone IN ("'.implode('","', $realDrivers).'");');
$realDriverIds = [
    1046,
    1026,
    1003,
    1004,
    1043,
    1054,
    1050,
    1045,
    1055,
    1056
];


$config = include APP_ROOT . '/../config/config.php';

echo '======[Guangzhou]producer-GPS Server Start====', PHP_EOL;

$redis = new Redis();
$redis->connect($config['redis_host'], $config['redis_port']) or die('Redis connect failed!');
if (isset($config['redis_pass'])) {
    $redis->auth($config['redis_pass']) or die('Redis auth failed!');
}
if (isset($config['redis_db'])) {
    $redis->select($config['redis_db']) or die('Redis select db failed!');
}

while (1) {
    $startTime = microtime(1);
    // ----------

    foreach ($realDriverIds as $index => $driverId) {
        if (!$driverId) {
            continue;
        }
        $driverGPS = $redis->hGetAll('driver:netcar:position:hash:' . $driverId);
        if (!$driverGPS) {
            continue;
        }

        //_log($driverGPS);

        _log($driverId);

        if (!$driverGPS['on_status']) {
            continue;
        }

        if ($driverGPS['timestamp'] < time() - 30) {
            continue;
        }

        $fields = [
            'companyId'         => 'syjcx',
            'address'           => '500100',
            'driverRegionCode'  => '500100',
            'vehicleNo'         => $drivers[$index]['vehicleNo'],
            'plateColor'        => '蓝色',
            'vehicleRegionCode' => '500100',
            'positionTime'      => date('YmdHis', $driverGPS['timestamp']),
            'longitude'         => str_replace('.', '', $driverGPS['longitude']),
            'latitude'          => str_replace('.', '', $driverGPS['latitude']),
            'speed'             => '1',
            'direction'         => '23',
            'elevation'         => '101',
            'mileage'           => '2',
            'encrypt'           => '1',
            'warnStatus'        => '',
            'vehStatus'         => '',
            'bizStatus'         => '3',//1：载客 2：接单 3：空驶 4：停运
            'orderId'           => '',
            'driverName'        => $drivers[$index]['driverName'],
            'driverId'          => $driverId,
            'driverCertCard'    => $drivers[$index]['licenseId'],
            'vehicleType'       => '小轿车',
            'positionType'      => 'AUTO',//SJSB:司机上班、SJXB:司机下班、CKSC:乘客上车、CKXC:乘客下车、AUTO:定时上传、DDPD:派单
            'validity'          => '1',
        ];

        if ($driverGPS['service_status']) {
            $orders = $redis->hGetAll('netcar_order_driver_' . $driverId);
            /*
             * timely15325129038868
            {
              "order_type": "1",
              "passenger_id": "9488"
            }
            */
            foreach ($orders as $orderNum => $tmpOrder) {
                // 进行中的订单在redis中不删除，保存上车时间和总里程
                if ($orderNum && $order = $redis->hGetAll(md5($orderNum))) {
                    if (in_array(intval($order['order_state']), [1, 2, 3, 5, 7, 8, 9])) {
                        $fields['bizStatus'] = 1;//$order['order_state'] == 1 ? 1 : 2;
                        $fields['orderId'] = $orderNum;
                        break;
                    }
                }
            }
        }

        $fileName = 'syjcx_GPS_' . $apiName . '_REQ_' . date('YmdHisB') . '.json';
        $content = json_encode($fields);

        $redis->lPush('guangdong:queue', "$fileName|$content");

        echo $fileName, PHP_EOL;
    }

    // ----------
    if (($leftTime = $startTime + 30 - microtime(1)) > 0) {
        echo $leftTime, PHP_EOL;
        usleep($leftTime * 1000000);
    } else {
        echo $leftTime, PHP_EOL;
    }
}


//=========

/**
 * 打印 for 测试
 */
function _log()
{
    static $files = [];
    $bt = debug_backtrace();
    $caller = array_shift($bt);
    if (!isset($files[$caller['file']])) {
        $files[$caller['file']] = file($caller['file']);
    }

    preg_match('#\((.*)\)#i', $files[$caller['file']][$caller['line'] - 1], $params);

    echo "\nline:", $caller['line'], ": ", $params[1], "> ";

    if (func_num_args() > 1) {
        print_r(func_get_args());
    } else {
        $v = func_get_arg(0);
        if (is_array($v) || is_object($v)) {
            var_dump($v);
        } else {
            echo $v;
        }
    }
}